/**
 * zbestpayment.com Inc.
 * Copyright (c) 2004-2017 All Rights Reserved.
 */
package com.zbest.zpay.gw.dispatch;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zbest.common.lang.http.HttpClientTemplate;
import com.zbest.zpay.gw.cache.CommunicationConfigCache;
import com.zbest.zpay.gw.dal.model.GwCommunicationConfigDO;
import com.zbest.zpay.gw.model.MessageContext;
import com.zbest.zpay.gw.model.MethodType;
import com.zbest.zpay.gw.model.SslStatus;

/**
 * 
 *
 * @author Administrator
 * @version $Id: HttpMessageDispatcher.java, v 0.1 2017-4-12 下午11:32:35 Administrator Exp $
 */
@Service("httpMessageDispatcher")
public class HttpMessageDispatcher implements MessageDispatcher {

    private Map<String, HttpClientTemplate> httpTemplates = new HashMap<String, HttpClientTemplate>();

    @Resource
    private CommunicationConfigCache        communicationConfigCache;

    /** 
     * @see com.zbest.zpay.gw.dispatch.MessageDispatcher#send(com.zbest.zpay.gw.model.MessageContext)
     */
    @Override
    public void send(MessageContext context) {

        GwCommunicationConfigDO gwCommunicationConfigDO = communicationConfigCache.get(context
            .getChannelId());

        HttpClientTemplate httpClientTemplate = httpTemplates.get(context.getChannelId());
        if (httpClientTemplate == null) {
            synchronized (gwCommunicationConfigDO) {
                if (httpTemplates.get(context.getChannelId()) == null) {
                    if (gwCommunicationConfigDO.getSslStatus().equals(SslStatus.YES.getCode())) {
                        httpClientTemplate = new HttpClientTemplate(null, null);
                    } else {
                        httpClientTemplate = new HttpClientTemplate();
                    }
                    httpTemplates.put(gwCommunicationConfigDO.getChannelId(), httpClientTemplate);
                } else {
                    httpClientTemplate = httpTemplates.get(context.getChannelId());
                }

            }
        }

        if (gwCommunicationConfigDO.getMethod().equals(MethodType.GET.name())) {
            String response = httpClientTemplate.get(gwCommunicationConfigDO.getRemoteAddress(),
                gwCommunicationConfigDO.getCharset());
            context.setReceiveMessage(response);
        } else if (gwCommunicationConfigDO.getMethod().equals(MethodType.POST.name())) {
            String response = httpClientTemplate.post(gwCommunicationConfigDO.getRemoteAddress(),
                (String) context.getSendMessage(), gwCommunicationConfigDO.getCharset());
            context.setReceiveMessage(response);
        }

    }

}
